package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.util.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class SearchController {

    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String,String> searchMap){
        //因为是get请求，可能会有中文乱码问题，要转换为utf-8
        try {
            searchMap = WebUtil.convertCharsetToUTF8(searchMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //如果前端没有传页码，自己设置初始值为1
        if(searchMap.get("pageNo")==null){
            searchMap.put("pageNo","1");
        }

        //排序参数容错处理
        if(searchMap.get("sort")==null){
            searchMap.put("sort","");
        }
        if(searchMap.get("sortOrder")==null){
            searchMap.put("sortOrder","DESC");
        }




        //去elasticsearch中搜索结果
        Map result = skuSearchService.search(searchMap);
        model.addAttribute("result",result);

        //url处理
        StringBuffer url = new StringBuffer("/search.do?");
        for(String key:searchMap.keySet()){
            url.append("&"+key+"="+searchMap.get(key));
        }
        System.out.println(url);
        model.addAttribute("url",url);

        //筛选条件回显
        model.addAttribute("searchMap",searchMap);

        //当前页码回显,返回的是个int型对象，可以与前端进行比较
        int pageNo = Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo",pageNo);

        int startPage=1;//开始页为1
        Long totalPages = (Long) result.get("totalPages");//得到总页数
        int endPage = totalPages.intValue();//截止页
        if(totalPages>5){
            startPage=pageNo-2;
            if(startPage<1){
                startPage=1;
            }
            endPage=startPage+4;
        }
        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);

        return "search";

    }
}
